<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition End User License Agreement
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magento.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     Mage_Customer
 * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license http://www.magento.com/license/enterprise-edition
 */

/**
 * API2 class for customer (admin)
 *
 * @category   Mage
 * @package    Mage_Customer
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class ApiCenter_SalesApi_Model_Api2_Orderapi_Rest_Admin_V1 extends ApiCenter_SalesApi_Model_Api2_Orderapi_Rest
{
    /**
     * Retrieve information about specified order item
     *
     * @throws Mage_Api2_Exception
     * @return array
     */
    const UNCONFIRMED="5";
    
    const  SFCODE ="";
    
    protected function _retrieve()
    {

        try{
        $orderId    = $this->getRequest()->getParam('id');
        $vendorId  =$this->getRequest()->getParam('vendorid');
        
        $collection = $this->_getCollectionForSingleRetrieve($orderId,$vendorId);
       
        $order = $collection->getItemById($orderId);
       
        if (!$order) {
            $this->_critical(self::RESOURCE_NOT_FOUND ,400);
        }
        $orderData =$order->getData();
       
        $addresses = $this->_getAddresses(array($orderId));
        $items     = $this->_getItems(array($orderId));
      
        if ($addresses) {
            $orderData['addresses'] = $addresses[$orderId];
        }
        if ($items) {
            $orderData['order_items'] = $items;
        }
        $orderData['ordertracking'] =$this->getOdertrackingInfo($order->getIncrementId());
        $res['status']=1;
        $res['info'] = $orderData;
        }catch(Exception $e){
            $res['status']=0;
            $res['info']=$e->getMessage();
        }
        return $res;
    }
    /**
     * TODO
     *
     * @return int
     */
    protected function _retrieveCollection() {
        $ordersData=array();
        $noConfirmorder= array();
        /** @var $salesHelper ApiCenter_SalesApi_Helper_Data */
        $salesHelper = Mage::helper("salesapi");
        $vendorId  =$this->getRequest()->getParam('vendorid');
        $status  =$this->getRequest()->getParam('status');
        $filter = $this->getRequest()->getFilter();
        //不同的筛选条件，会查不同的数据源
        $collection = $this->_getCollectionForRetrieve($vendorId);
        
        try {

       if($status == ApiCenter_SalesApi_Model_Api2_Orderapi::IS_CONFIRM){
           $filter_tbOrder = $collection->getData();
           foreach ($filter_tbOrder as $k =>$order) {
             $parent_IncrementId = substr($order['increment_id'],0,9);
             $ordersData[$parent_IncrementId]['items'][]=$order;
             $ordersData[$parent_IncrementId]['created_at']=$order['main_created'];
             $ordersData[$parent_IncrementId]["canPass"]="0"; //业务不允许确认的订单
             $ordersData[$parent_IncrementId]["canAddress"]="0";
             if(!$this->_isDividedAllOrder($order,$parent_IncrementId, $vendorId)){
                $ordersData[$parent_IncrementId]["canPass"]="1"; //业务需要确认的订单
             }
             if($order["v_send_bsp_status"]!=="OK"){
               $ordersData[$parent_IncrementId]["canAddress"]="1";
             }
           }
         

       }elseif($status == ApiCenter_SalesApi_Model_Api2_Orderapi::NO_CONFIRM){
           /*canPass 表示是否分单已经分完*/
           foreach ($collection->getItems() as $order) {
                                   $noConfirmorder[$order->getIncrementId()]['items']=array();
                                   $noConfirmorder[$order->getIncrementId()]['price']=$order->getSumPrice();
                                   $noConfirmorder[$order->getIncrementId()]['created_at']=$order->getMainCreatedAt();
                                   $noConfirmorder[$order->getIncrementId()]['status']=$order->getMainStatus();
                               if($salesHelper->_businessFilterOrder($order->getOrderId(),$vendorId)){
                                   $noConfirmorder[$order->getIncrementId()]["canPass"]="1"; //业务不允许确认的订单
                               }
                           
           }
               $ordersData=$noConfirmorder;
            }
            $ordersData['total'] =$this->_getCountForRetrieve($vendorId);
            $res['status']=1;
            $res['info']=$ordersData;
            } catch (Exception $e) {
                $res['status']=0;
                $res['info']=$e->getMessage();
            }
            return $res;
         
     }

     protected function _loadChildOrder($pid,$vendorId){
         /** @var $collection ApiCenter_SalesApi_Model_Resource_Mysql4_Order_Collection */
        $collection = Mage::getResourceModel('salesapi/order_collection');
        $collection->addFieldToFilter("main_table.vendor_id",$vendorId);
		$collection->addFieldToFilter("main_table.increment_id",array("like"=>$pid."%"));
		 
		return $collection->getData();
     }
     
     protected  function _loadOrderItem($order_id,$vendorId){
            $collection = Mage::getResourceModel("sales/order_item_collection");
            $collection-> addFieldToFilter("main_table.vendor_id",$this->_loadVendor($vendorId)->getId());
            $collection->addFieldToFilter("main_table.parent_item_id",array('null' => ''));
            $collection->addFieldToFilter("order_id",$order_id);
             $data = $collection->getData();
         //$dividedOrder =
         
             return $data;
     }
     
    /*判断是否已经分完单当前de单*/
     protected function _isDividedAllOrder($tb_order,$orderId,$vendorId){
         $check_info =array();

             $items = $this->_getItems(array($tb_order["entity_id"]));
             //算出所有已分单相同sku各自库存总数
             foreach($items as $_item){
                 $check_info[$_item['sku']]['qty']=$_item['qty_ordered']+@$check_info[$_item['sku']]['qty'];
             }

         $items_info = $this->_loadOrderItem($orderId, $vendorId);
         foreach ($check_info as $sku=>$b){
             foreach ($items_info as $v){
                 if($v['sku']==$sku && $v['qty_ordered']!=$b['qty']){
                        return false; 
                 }
             }
         }
         return true; 
     }
   
     
}